package org.thanos.simulator.api;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.Objects;

public class MQTTClientApi {

    private static volatile MqttClient mqttClient;

    public static MqttClient init(String broker, String clientId, String username, String password) throws MqttException {
        if (Objects.isNull(mqttClient)) {
            synchronized (MQTTClientApi.class) {
                if (Objects.isNull(mqttClient)) {
                    mqttClient = new MqttClient(broker, clientId, new MemoryPersistence());
                    MqttConnectOptions options = new MqttConnectOptions();
                    options.setCleanSession(true);
                    options.setConnectionTimeout(10);
                    options.setKeepAliveInterval(20);
                    options.setMaxInflight(10000);
                    options.setUserName(username);
                    options.setPassword(password.toCharArray());
                    mqttClient.connect(options);
                }
            }
        }
        return mqttClient;
    }

    public static boolean isInitialized() {
        return Objects.nonNull(mqttClient) && mqttClient.isConnected();
    }

    public static void disconnected() throws MqttException {
        if (Objects.nonNull(mqttClient)) {
            mqttClient.disconnect();
            mqttClient.close();
            mqttClient = null;
        }
    }

    public static void subscribe(String topic, Integer qos) throws MqttException {
        mqttClient.subscribe(topic, qos);
    }
}
